package com.yang.biz.modular.excel.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.yang.biz.api.ExcelApi;
import com.yang.biz.modular.excel.result.EarthquakeExcelResult;
import com.yang.common.exception.CommonException;
import com.yang.common.util.CommonServletUtil;
import com.yang.biz.modular.excel.util.Excel2Util;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author: yangjianzhi
 * @version1.0
 */
@Api(tags = "Excel工具控制器")
@RestController
@Validated
public class ExcelController {

    @Resource
    private ExcelApi excelApi;

    /**
     * 测试
     */
    @ApiOperation("测试")
    @GetMapping("/biz/excel/test")
    public ResponseEntity<byte[]> doLogin() {
        return excelApi.downloadImportTemplate(EarthquakeExcelResult.class);
    }

    /**
     * 导出数据到excel
     */
    @ApiOperationSupport(order = 1)
    @ApiOperation("导出数据到excel")
    @PostMapping("/biz/excel/export")
    public void epxort(@RequestBody List<Map<String, String>> titleValueMapList) {
        if (ObjectUtil.isEmpty(titleValueMapList)) {
            throw new CommonException("不可导出空数据");
        }
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(titleValueMapList, true);
        Excel2Util.exportExcel(CommonServletUtil.getResponse(), "导出数据", writer);
    }
}
